#include "ExceptionHandler.h"
#include "GlobalFunction.h"
#include <DbgHelp.h>
#include <io.h>
#include <direct.h>
#include <Shlwapi.h>
#include <stdio.h>
#include <hge.h>
//////////////////////////////////////////////////////////////////////////
LONG WINAPI BM_UnhandledExceptionFilter(_EXCEPTION_POINTERS* pExceptionInfo)
{
#ifdef _DEBUG
	// In debug mode, do not record dump file
	return EXCEPTION_EXECUTE_HANDLER;
#endif
	char szBuf[MAX_PATH];
	sprintf(szBuf, "%s\\Dump",
		GetRootPath());

	if(!PathFileExists(szBuf))
	{
		mkdir(szBuf);
	}

	SYSTEMTIME st;
	GetLocalTime(&st);
	sprintf(szBuf, "%s\\Dump\\CLIENT_%02d-%02d-%02d-%02d-%02d.dmp",
		GetRootPath(), st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute);

	HANDLE hFile = ::CreateFile(  
		szBuf,   
		GENERIC_WRITE,   
		0,   
		NULL,   
		CREATE_ALWAYS,   
		FILE_ATTRIBUTE_NORMAL,   
		NULL);
	if(hFile != INVALID_HANDLE_VALUE)
	{
		MINIDUMP_EXCEPTION_INFORMATION einfo;
		einfo.ThreadId = GetCurrentThreadId();
		einfo.ExceptionPointers = pExceptionInfo;
		einfo.ClientPointers = FALSE;

		MiniDumpWriteDump(GetCurrentProcess(),
			GetCurrentProcessId(),
			hFile,
			MiniDumpWithFullMemory,
			&einfo,
			NULL,
			NULL);

		CloseHandle(hFile);
	}

	sprintf(szBuf, "Exception!Address:%08X Code:%d",
		(DWORD)pExceptionInfo->ExceptionRecord->ExceptionAddress,
		pExceptionInfo->ExceptionRecord->ExceptionCode);

	AfxGetHge()->System_Log(szBuf);
	AfxGetHge()->System_Log("Stack information generated by StackWalker:");
	StackWalkerLog sw;
	sw.ShowCallstack(GetCurrentThread(), pExceptionInfo->ContextRecord);

	MessageBox(NULL, szBuf, "EXCEPTION", MB_ICONERROR | MB_TASKMODAL);

	return EXCEPTION_EXECUTE_HANDLER;
}


//////////////////////////////////////////////////////////////////////////
void StackWalkerLog::OnOutput(LPCSTR szText)
{
	AfxGetHge()->System_Log(szText);
}